import React, { Component } from 'react';
import {
  StyleSheet, View, Text, Dimensions, SwipeableFlatList, TouchableOpacity, Image, ActivityIndicator, Alert,
} from 'react-native';
import PropTypes from 'prop-types';
import SearchBox from '../../utils/SearchBox';
import CustomErrorView from '../../utils/CustomErrorView';
import CustomLoadingView from '../../utils/CustomLoadingView';
import myStyles from '../../utils/myStyles';
import ClientUtil from '../../utils/ClientUtil';
import HTTPUtil from '../../utils/HTTPUtil';
import handleData from './handleData';

const GET_TEMPLATE_LIST = `${ClientUtil.HOST}/bff/employeeDailyReport/page/`;
const SUBMIT_ONE_DAY_ALL_GS = `${ClientUtil.HOST}/bff/employeeDailyReport/`;
let isLoadMore = false;

class Templateist extends Component {
  static propTypes = {
    selectedDate: PropTypes.string,
    headers: PropTypes.object,
    onClose: PropTypes.func,
  };

  constructor(props) {
    super(props);
    this.state = {
      errorMsg: '',
      isLoading: true,
      pageNo: 1, // 当前页, 0表示 所有页都加载完成
      searchTxt: '', // 搜索文本
      selectedTempId: '',
      templateIdList: [],
      templateList: [], // 模板列表
    };
  }

  componentDidMount() {
    isLoadMore = false;
    this.getList();
  }

  getList() {
    console.log('getList pageNo:', this.state.pageNo);
    const that = this;
    let {
      pageNo, searchTxt, selectedTempId, templateList, templateIdList,
    } = this.state;
    const url = `${GET_TEMPLATE_LIST}?status=01&pageNo=${pageNo}&name=${searchTxt}`;
    HTTPUtil.getHasToken(url, this.props.headers).then((res) => {
      console.log('getTemplateList res:', res);
      isLoadMore = false;
      if (res.records) {
        if (pageNo === 1 && searchTxt) { // 模糊搜索
          templateList = [];
          templateIdList = [];
          selectedTempId = '';
        }
        if (res.pages > pageNo) {
          that.setState((state) => ({ pageNo: state.pageNo + 1 }));
        } else {
          that.setState({ pageNo: 0 });
        }
        if (res.records.length) {
          if (!selectedTempId && !templateList.length) { // 默认选择第一个模板
            selectedTempId = res.records[0].id || '';
          }
          res.records.forEach((item) => {
            if (item.id && !templateIdList.includes(item.id)) {
              templateIdList.push(item.id);
              templateList.push({
                tempId: item.id || '',
                tempName: item.name || '',
                checked: selectedTempId === item.id,
              });
            }
          });
          console.log('getTemplateList templateList:', templateList);
          that.setState({
            templateList, templateIdList, selectedTempId, isLoading: false, errorMsg: '',
          });
        } else {
          console.log('getTemplateList 没有模板:', res);
          that.setState({ isLoading: false, errorMsg: '没有模板，请新建一个！' });
        }
      } else {
        console.log('getTemplateList 数据格式有误:', res);
        that.setState({ isLoading: false, errorMsg: '获取模板失败，数据格式有误！' });
      }
    }).catch((error) => {
      console.log('getTemplateList error:', error);
      that.setState({ isLoading: false, errorMsg: '获取模板失败，请检查网络后重试！' });
    });
  }

  // 上拉加载更多数据
  loadMoreData = () => {
    console.log('loadMoreData 上拉加载更多数据');
    if (this.state.pageNo && !isLoadMore) {
      isLoadMore = true;
      this.getList();
    }
  }

  onTemplateSelected(idx) {
    const { templateList } = this.state;
    templateList.forEach((item, index) => {
      item.checked = index === idx;
    });
    console.log(`onTemplateSelected idx:${idx}  templateList:`, templateList);
    this.setState({ templateList });
  }

  onTemplateSureClick = () => {
    console.log('onTemplateSureClick');
    const that = this;
    const selectedDate = this.props.selectedDate;
    if (that.state.errorMsg) {
      that.props.onClose();
      return;
    }
    const list = that.state.templateList.filter((item) => item.checked);
    if (list.length) {
      const selectedTempId = list[0].tempId;
      console.log('onTemplateSureClick selectedTempId:', selectedTempId);
      HTTPUtil.getHasToken(SUBMIT_ONE_DAY_ALL_GS + selectedTempId, that.props.headers)
        .then((result) => {
          console.log('onTemplateSureClick result:', result);
          let notEstContent = {};// 一个月的未立项项目内容
          if (result.employeeDailyReportDto && result.employeeDailyReportDto.notEstContent) {
            notEstContent = JSON.parse(result.employeeDailyReportDto.notEstContent || '{}');
          }
          let notEstContentThisMonth = {};// 一个月的未立项项目内容
          if (result.employeeDailyReportDto && result.employeeDailyReportDto.notEstContentThisMonth) {
            notEstContentThisMonth = JSON.parse(result.employeeDailyReportDto.notEstContentThisMonth || '{}');
          }
          console.log('onTemplateSureClick notEstContentThisMonth', notEstContentThisMonth);
          const proList = result.proQualityReportHoursDto || [];// 生产性项目列表
          const notProList = result.unProQualityReportHoursDto || [];// 非生产性项目列表
          const { sectionsList, notHasProIdContent } = handleData.calculateSectionList(proList, notProList, selectedDate, 1, notEstContent);
          console.log('onTemplateSureClick getAllProjectByDay sectionsList:', sectionsList);
          that.props.onClose({
            selectedTempId,
            sectionsList,
            notEstContent,
            notEstContentThisMonth,
            notHasProIdContent,
          });
        }).catch((error) => {
          console.log('onTemplateSureClick error:', error);
          Alert.alert('提示', '获取模板详情失败，请检查网络后重试！', { cancelable: false });
        });
    } else {
      Alert.alert(
        '提示',
        '您未选中任何模板！',
        [
          { text: '取消', style: 'cancel' },
          { text: '确定', onPress: () => that.props.onClose() },
        ],
      );
    }
  }

  onTemplateDelete = (tempId, idx) => {
    const that = this;
    console.log(`onTemplateDelete idx:${idx} tempId:`, tempId);
    HTTPUtil.deleteHasToken(SUBMIT_ONE_DAY_ALL_GS + tempId, this.props.headers).then((res) => {
      console.log('onTemplateDelete res: ', res);
      const templateList = that.state.templateList;
      templateList.splice(idx, 1);
      that.setState({ templateList });
      Alert.alert('提示', '删除模板成功！', { cancelable: false });
    }).catch((error) => {
      console.log('onSaveTemplate error: ', error);
      Alert.alert('提示', `删除模板失败，错误：${error.message}`, { cancelable: false });
    });
  }

  renderRow({ item, index }) {
    return (
      <TouchableOpacity key={item.tempId} onPress={() => this.onTemplateSelected(index)}>
        <View style={[styles.listItem, myStyles.flexRowSpaceBetween]}>
          <View style={[styles.projectInfo, myStyles.lineBorderBottom]}>
            <Text style={[styles.projectText, item.checked && styles.checkedText]} numberOfLines={1}>{item.tempName}</Text>
          </View>
          <View style={{ width: 20 }}>
            <Image
              style={[styles.iconChecked, { display: item.checked ? 'flex' : 'none' }]}
              source={require('../../images/utils/menu_check.png')}
            />
          </View>
        </View>
      </TouchableOpacity>
    );
  }

  renderQuickActions({ item, index }) {
    return (
      <View style={styles.quickActions}>
        <TouchableOpacity
          onPress={() => {
            Alert.alert(
              '提示',
              '确定删除?',
              [
                { text: '取消', style: 'cancel' },
                {
                  text: '确定',
                  onPress: () => this.onTemplateDelete(item.tempId, index),
                },
              ],
              { cancelable: false },
            );
          }}
        >
          <View style={styles.quick}>
            <Text style={styles.text}>删除</Text>
          </View>
        </TouchableOpacity>
      </View>
    );
  }

  render() {
    let view = null;
    if (this.state.isLoading) {
      view = <CustomLoadingView />;
    } else if (this.state.errorMsg) {
      view = <CustomErrorView errorInfo={this.state.errorMsg} />;
    } else {
      view = (
        <View style={{flex:1}}>
          <SearchBox handler={(searchTxt) => {
            isLoadMore = true;
            this.setState({ searchTxt, pageNo: 1 }, () => this.getList());
          }}
          />
          <SwipeableFlatList
            style={styles.listView}
            data={this.state.templateList}
            ItemSeparatorComponent={() => <View style={myStyles.lineBorderBottom} />}
            renderItem={this.renderRow.bind(this)}
            ListFooterComponent={() => {
              if (this.state.pageNo) {
                return (// 设置上拉加载布局
                  <View style={styles.loadMore}>
                    <ActivityIndicator
                      style={styles.indicator}
                      size="large"
                      color="red"
                      animating
                    />
                    <Text style={{ textAlign: 'center' }}>正在加载更多</Text>
                  </View>
                );
              }
              return null;
            }}
            onEndReached={this.loadMoreData}
            // 侧滑删除
            maxSwipeDistance={100}
            bounceFirstRowOnMount={false} // 关闭自动回去，重要，否则无法侧滑删除
            renderQuickActions={this.renderQuickActions.bind(this)}
          />
        </View>
      );
    }
    return (
      <View style={styles.container}>
        <View style={styles.paddingView} />
        <View style={styles.popView}>
          <View style={[styles.popTitle, myStyles.flexRowSpaceBetween, myStyles.lineBorderBottom]}>
            <TouchableOpacity onPress={() => this.props.onClose()}>
              <Text style={styles.titleText}>取消</Text>
            </TouchableOpacity>
            <Text style={styles.titleText}>请选择模板</Text>
            <TouchableOpacity onPress={this.onTemplateSureClick}>
              <Text style={styles.titleText}>确定</Text>
            </TouchableOpacity>
          </View>
          {view}
        </View>
      </View>
    );
  }
}
const weekDayHeight = (Dimensions.get('window').width - 16) / 7.0 + 71;
const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  paddingView: {
    height: weekDayHeight + 8 + 64, // 64 是原生标题栏的高度
    backgroundColor: '#000000',
    opacity: 0.5,
  },
  popView: {
    flex: 1,
    backgroundColor: '#f6f6f6',
  },
  popTitle: {
    height: 48,
    padding: 10,
    backgroundColor: '#ECEDEE',
  },
  titleText: {
    fontSize: 16,
  },
  listView: {

  },
  listItem: {
    paddingLeft: 16,
    paddingRight: 16,
    backgroundColor: 'white',
  },
  projectInfo: {
    marginLeft: 10,
    paddingVertical: 30,
    flex: 1,
  },
  projectText: {
    fontSize: 14,
    color: '#4A4A4A',
  },
  checkedText: {
    color: '#3295F9',
  },
  iconChecked: {
    width: 20,
  },
  quickActions: {
    flex: 1,
    marginTop: 15,
    flexDirection: 'row',
    justifyContent: 'flex-end',
    marginRight: 15,
    marginBottom: 15,
  },
  quick: {
    backgroundColor: 'red',
    flex: 1,
    alignItems: 'flex-end',
    justifyContent: 'center',
    padding: 10,
    width: 200,

  },
  text: {
    color: 'white',
    fontWeight: 'bold',
  },
});
export default Templateist;
